<template>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" draggable :close-on-click-modal="false" align-center>
        <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
            <el-row>
                <el-col :span="24" v-show="form.menuType != 2">
                    <el-form-item label="上级菜单">
                        <el-tree-select v-model="form.parentId" :data="menuOptions"
                            :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                            placeholder="选择上级菜单" check-strictly />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="功能类型" prop="menuType">
                        <el-radio-group v-model="form.menuType" :disabled="Boolean(form.id)">
                            <el-radio v-for="item in props.menuTypes" :key="item.value" :value="item.value">
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="菜单名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入菜单名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="功能标识" prop="funcKey">
                        <template #label>
                            <span>
                                <el-tooltip content="用来代表功能的唯一标识符，如：feature:menu" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                功能标识
                            </span>
                        </template>
                        <el-input v-model="form.funcKey" placeholder="请输入功能标识" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 0">
                    <el-form-item prop="perm">
                        <el-select-v2 v-model="form.perm" maxlength="100" filterable remote :remote-method="permRemote"
                            multiple collapse-tags collapse-tags-tooltip clearable :options="permOptions"
                            :loading="permLoading" placeholder="请输入接口权限串">
                            <template #prefix>
                                <el-icon>
                                    <search />
                                </el-icon>
                            </template>
                            <template #default="{ item }">
                                <span style="margin-right: 8px">{{ item.text }}</span>
                                <span style="color: var(--el-text-color-secondary); font-size: 13px">
                                    {{ item.value }}
                                </span>
                            </template>
                        </el-select-v2>
                        <template #label>
                            <span>
                                <el-tooltip content="接口管理中定义的接口权限，如：system:user:list，也可以自定义前端接口权限" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                接口权限
                            </span>
                        </template>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 2">
                    <el-form-item label="菜单图标" prop="icon">
                        <el-popover placement="bottom-start" :width="540" trigger="click">
                            <template #reference>
                                <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
                                    <template #prefix>
                                        <IconPlus v-if="form.icon" :name="form.icon" />
                                        <el-icon v-else style="height: 32px;width: 16px;">
                                            <search />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </template>
                            <icon-select ref="iconSelectRef" @selected="iconSelected" :active-icon="form.icon" />
                        </el-popover>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示排序" prop="order">
                        <el-input-number v-model="form.order" controls-position="right" :min="0" />
                    </el-form-item>
                </el-col>

                <el-col :span="12" v-if="form.menuType == 1">
                    <el-form-item prop="routeName">
                        <template #label>
                            <span>
                                <el-tooltip
                                    content="默认不填则和路由地址相同：如地址为：`user`，则名称为`User`（注意：因为router会删除名称相同路由，为避免名字的冲突，特殊情况下请自定义，保证唯一性）"
                                    placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                路由名称
                            </span>
                        </template>
                        <el-input v-model="form.routeName" placeholder="请输入路由名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 2">
                    <el-form-item>
                        <template #label>
                            <span>
                                <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>是否外链
                            </span>
                        </template>
                        <el-radio-group v-model="form.isFrame">
                            <el-radio :value="true">是</el-radio>
                            <el-radio :value="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 2">
                    <el-form-item prop="path">
                        <template #label>
                            <span>
                                <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                路由地址
                            </span>
                        </template>
                        <el-input v-model="form.path" placeholder="请输入路由地址" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType == 1">
                    <el-form-item prop="component">
                        <template #label>
                            <span>
                                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                组件路径
                            </span>
                        </template>
                        <el-input v-model="form.component" placeholder="请输入组件路径" />
                    </el-form-item>
                </el-col>

                <el-col :span="12" v-if="form.menuType == 1">
                    <el-form-item>
                        <el-input v-model="form.query" placeholder="请输入路由参数" maxlength="255" />
                        <template #label>
                            <span>
                                <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                路由参数
                            </span>
                        </template>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType == 1">
                    <el-form-item>
                        <template #label>
                            <span>
                                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                是否缓存
                            </span>
                        </template>
                        <el-radio-group v-model="form.isCache">
                            <el-radio :value="true">缓存</el-radio>
                            <el-radio :value="false">不缓存</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 2">
                    <el-form-item>
                        <template #label>
                            <span>
                                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                显示状态
                            </span>
                        </template>
                        <el-radio-group v-model="form.visible">
                            <el-radio v-for="dict in sys_show_hide" :key="dict.value" :value="dict.value">{{ dict.label
                                }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item>
                        <template #label>
                            <span>
                                <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                状态
                            </span>
                        </template>
                        <el-radio-group v-model="form.isActive">
                            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{
                                dict.label
                                }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script setup>
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from "@/api/system/menu";
import IconSelect from "@/components/IconSelect";
import { apipermissionsOptions } from "@/api/system/apipermissions"
const menuId = defineModel({
    type: [Number, String],
    default: undefined
})

const props = defineProps({
    menuTypes: {
        type: Array,
        default: () => [
            { value: 0, label: "目录" },
            { value: 1, label: "菜单" },
            { value: 2, label: '按钮' }
        ],
    }
})

const { proxy } = getCurrentInstance();
const permLoading = ref(false)
const menuRef = ref();
const permOptions = ref([]);
const open = ref(false);
const iconSelectRef = ref();
const menuOptions = ref([]);
const form = ref({});
const title = ref();
const loading = ref(false);

const emits = defineEmits(['confirmEvent'])

const rules = {
    name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    order: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }]
};

const { sys_show_hide, sys_normal_disable, sys_yes_no } = proxy.useDict("sys_show_hide", "sys_normal_disable", "sys_yes_no");

const permRemote = (keyword) => {
    permLoading.value = true;
    apipermissionsOptions(keyword).then(res => {
        permOptions.value = res.filter(item => item.permissionKey).map(item => ({
            value: item.permissionKey,
            label: item.permissionKey,
            text: item.name
        }));
    }).finally(() => {
        permLoading.value = false;
    })
}


/** 提交按钮 */
function submitForm() {
    menuRef.value.validate().then(() => {
        const isUpdate = form.value.id !== undefined;
        const serviceCall = isUpdate ? updateMenu(form.value) : addMenu(form.value);
        const successMessage = isUpdate ? "修改成功" : "新增成功";

        serviceCall.then(() => {
            proxy.$modal.msgSuccess(successMessage);
            open.value = false;
        }).then(() => {
            emits("confirmEvent", form.value);
        });
    })
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    // reset();
}


/** 表单重置 */
function reset() {
    form.value = {
        id: undefined,
        // parentId: 0,
        parentId: undefined,
        name: undefined,
        icon: undefined,
        menuType: 0,
        order: 0,
        isFrame: false,
        isCache: true,
        visible: true,
        isActive: true
    };
    proxy.resetForm("menuRef");
}


/** 选择图标 */
function iconSelected(name) {
    form.value.icon = name;
}


/** 展示下拉图标 */
function showSelectIcon() {
    iconSelectRef.value.reset();
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
    menuOptions.value = [];
    let q = { menuType: [0, 1] }
    return listMenu(q).then(response => {
        const menu = { id: '0', name: "主类目", children: [] };
        menu.children = proxy.handleTree(response);
        menuOptions.value.push(menu);
        return menuOptions.value;
    });
}

const show = (options) => {
    reset();
    form.value = { ...form.value, ...(options || {}) };
    open.value = true;
    if (menuId.value) {         //修改
        loading.value = true;
        Promise.all([getTreeselect(), getMenu(menuId.value)])
            .then(([menus, menu]) => {
                form.value = menu;
                title.value = "修改数据";
            })
            .finally(() => {
                loading.value = false;
            });
    } else {             //新增
        Promise.all([getTreeselect()])
            .then(([menus]) => {
                title.value = "添加数据";
            })
    }
}
const hidden = () => {
    open.value = false;
}

defineExpose({ show, hidden })

</script>
<style lang="scss"></style>